package com.zb.service.imp.sys;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.zb.dao.ext.charger.OmsChargerDao;
import com.zb.dao.ext.station.OmsStationAllDao;
import com.zb.dao.ext.station.OmsStationDao;
import com.zb.dao.ext.system.OmsOperMerchantDao;
import com.zb.entity.base.JsonCommon;
import com.zb.entity.base.JsonForList;
import com.zb.entity.base.JsonForMapDataList;
import com.zb.entity.base.JsonPageForList;
import com.zb.entity.base.OmsCommonParam;
import com.zb.entity.base.OmsHomePage;
import com.zb.entity.charger.OmsCharger;
import com.zb.entity.station.OmsStation;
import com.zb.entity.station.OmsStationAll;
import com.zb.entity.system.OmsOperMerchant;
import com.zb.service.sys.StationService;
import com.zb.tcp.rpc.as.SystemAppServerRpcClient;
import com.zb.tcp.rpc.as.client.entity.AppStationUpdateNotifyParam;
import com.zb.util.CarbonEmissionConverter;
import com.zb.util.OmsConstant;
import com.zb.util.StringUtil;
import com.zb.util.OmsConstant.MsgCodeEnum;
import com.zb.vo.oms.OmsStationVO;
import com.zb.vo.oms.StationExportVO;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class StationServiceImpl implements StationService{
	@Resource
	OmsStationDao omsStationDao;
	@Resource
	OmsStationAllDao omsStationAllDao;
	@Resource
	OmsOperMerchantDao omsOperMerchantDao;
	@Resource
	OmsChargerDao omsChargerDao;
//	@Resource
//	SystemAppServerRpcClient systemAppServerRpcClient;
	
	private Log log = LogFactory.getLog(StationServiceImpl.class);

	@Override
	public JsonForList getStationList(OmsStation station,String oper_id) {
		return omsStationDao.getStationList(station, oper_id);
	}

	@Override
	public JsonForList getStationListByPage(OmsStation station, int pageNo,int pageSize,String sortName,int sortVal,String oper_id) {
		return omsStationDao.getStationListByPage(station, pageNo, pageSize, sortName, sortVal, oper_id);
	}	
	
	@Override
	public JsonForList addStation(OmsStation station) {
		JsonForList jsonAdd = new JsonForList();
		jsonAdd = omsStationDao.addStation(station);
//		
//		AppStationUpdateNotifyParam param = new AppStationUpdateNotifyParam();
//		param.setProvinceCode(station.getDistrict_code().substring(0, 2) + "0000");
//		SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
//		param.setUpdateTime(dateFormat.format(station.getCreate_time()));
//		JsonCommon<String> result = systemAppServerRpcClient.stationUpdateNotify(param);
//		log.debug("Result:" + result.getCode());
//		log.debug("Result:" + result.getMsg());
		
		return jsonAdd;
	}

	@Override
	public JsonForList updateStation(OmsStation station) {
		//如果站点归属实体发上变化，需要同时逻辑删除原实体的操作员与该站点的绑定关系
		OmsStation omsStationTmp =new OmsStation();
		OmsStation param = new OmsStation();
		param.setStation_id(station.getStation_id());
		omsStationTmp = omsStationDao.findOneExample(param, null, null);
		JsonForList json = new JsonForList();
		if(omsStationTmp!=null ){
			if(omsStationTmp.getOper_merchant_id()!=null&&!omsStationTmp.getOper_merchant_id().equals(station.getOper_merchant_id())){
				//删除对应关系
				omsStationDao.logicDelOperStationByOperId(station.getStation_id());		
			}			
		}else{
			json.setCode("400");
			json.setMsg("未找到该站点信息");
			return json;
		}		
		JsonForList jsonUpdate = new JsonForList();
		jsonUpdate = omsStationDao.updateStation(station);	
		
//		//通知app更新
//		AppStationUpdateNotifyParam appParam = new AppStationUpdateNotifyParam();
//		appParam.setProvinceCode(station.getDistrict_code().substring(0, 2) + "0000");
//		SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
//		appParam.setUpdateTime(dateFormat.format(station.getUpdate_time()));
//		JsonCommon<String> result = systemAppServerRpcClient.stationUpdateNotify(appParam);
//		log.debug("Result:" + result.getCode());
//		log.debug("Result:" + result.getMsg());
		
		return jsonUpdate;
	}

	@Override
	public JsonForList deleteStation(List<String> list) {
		return omsStationDao.deleteStation(list);
	}

	@Override
	public  List<OmsStation>  findAll() {
		OmsStation omsStation = new OmsStation();
		List<OmsStation> stationList = omsStationDao.findAll(omsStation);
		return stationList;
	}

	@Override
	public List<OmsStation> getStationByIds(String stationIds) {
		String[]  list =  stationIds.split(",");
//		list.
		StringBuilder sb = new StringBuilder("where 1=1 ");
		if(list.length>0){
			sb.append("and station_id in (");
			for(String str :list){
				sb.append("'"+str+"',");
			}
			sb.deleteCharAt(sb.length()-1);
			sb.append(")");
		}
		OmsStation station = new OmsStation();
		return omsStationDao.findListByCondition(station, sb.toString());
	}
	

	/************************20160324 perlin mod begin********************************************/
	@Override
	public JsonForList getStationListWithIgnore(OmsStation station,String oper_id) {
		StringBuffer conditionSql = new StringBuffer(" a ");
		conditionSql.append(" left join (select b.district_code dictrict_code_other, b.city_code,d.province_code from oms_dic_district_code b ,oms_dic_city_code c ,oms_dic_province_code d where b.city_code=c.city_code and c.province_code=d.province_code) dic_view ");
		conditionSql.append(" ON  dic_view.dictrict_code_other=a.district_code where a.valid_flag = 1 ");
		JsonForList<OmsStation> retJsons = new JsonForList<OmsStation>();
		retJsons.setList(omsStationDao.findListByConditionWithIgnore(station, conditionSql.toString()));
		retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
		retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		return retJsons;
	}
	
	@Override
	public List<OmsStation> getStationByDistrictCode(String province_code, String city_code, String district_code) {
		OmsStation omsStation = new OmsStation();
		StringBuffer conditionSql = new StringBuffer(" a ");
		if(!StringUtil.isBlank(district_code)){
			omsStation.setDistrict_code(district_code);
		}
		if(!StringUtil.isBlank(city_code)){
			conditionSql.append(" left join (select b.district_code dictrict_code_other, b.city_code from oms_dic_district_code b ,oms_dic_city_code c where b.city_code=c.city_code ) dic_view ");
			conditionSql.append(" ON  dic_view.city_code='"+city_code+"'");
			conditionSql.append(" where dic_view.dictrict_code_other=a.district_code and a.valid_flag = 1");			
		}
		if(!StringUtil.isBlank(province_code)){
			conditionSql.append(" left join (select b.district_code dictrict_code_other, b.city_code,d.province_code from oms_dic_district_code b ,oms_dic_city_code c ,oms_dic_province_code d where b.city_code=c.city_code and c.province_code=d.province_code) dic_view ");
			conditionSql.append(" ON  dic_view.province_code='"+province_code+"'");
			conditionSql.append(" where dic_view.dictrict_code_other=a.district_code and a.valid_flag = 1 ");
			omsStation.setProvince_code(province_code);
		}
		return omsStationDao.findListByConditionWithIgnore(omsStation, conditionSql.toString());
	}
	
	/************************20160324 perlin mod end********************************************/

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public JsonForList findAllOperMerchant() {
		List<OmsOperMerchant>  list =  omsOperMerchantDao.findAll(new OmsOperMerchant());
		JsonForList json = new JsonForList();
		json.setCode("200");
		json.setMsg("ok");
		json.setList(list);
		return json;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public JsonCommon getHomePageData(String charger_type) {
		//查询数据：
		//站：电站总数、运营中数量、规划中数量、建设中数量
		//桩：桩总数、故障数量、充电数量、预约数量、空闲数量、离线数量。
		//桩：上上月桩总数、上月桩总数、本月桩总数、本月预约数量、上月预约数量、本月充电数量、上月充电数量
		//返回数据：除了上上月桩总数换成上月桩增加数量外，其余就就是以上的
		//站：电站总数、运营中数量、规划中数量、建设中数量
		int operationNo = 0,planningNo = 0,makingNo = 0,stationTotal;
		JsonCommon json = new JsonCommon();
		OmsHomePage omsHomePage = new  OmsHomePage();
		String sql1 = "select current_state,count(current_state) as total from oms_station where valid_flag=1 group by current_state";//有效电站
		List<Map<String, Object>> list1 = omsStationDao.findDataBySql(sql1);
		if(list1.size()>0){
			for(Map<String, Object> map : list1){
				if(map.get("current_state").toString().equals("1")){//当前状态：1，运营中；2，安装中；3，规划中
					operationNo = Integer.valueOf(map.get("total").toString());
				}else if(map.get("current_state").toString().equals("2")){
					makingNo = Integer.valueOf(map.get("total").toString());
				}else if(map.get("current_state").toString().equals("3")){
					planningNo = Integer.valueOf(map.get("total").toString());
				}
			}
		}
		stationTotal = operationNo+planningNo+makingNo;
		//桩：桩总数、故障数量、充电数量、预约数量、空闲数量、离线数量。		
		String condition = null;
//		switch(charger_type){//charger_type:1为直流，2为交流，不传为查询全部
//		case "1":
//			condition = 
//			break;
//		}
//		oms_charger_state_direct[直流充电桩状态表] online_status  1代表在线  0代表离线    charge_status 0: 空闲;1: 预约;2 充电; 3 故障
		int offlineNo_d=0,offlineNo_a=0,chargerOfflineNo =0;
//		//String sql2_d_offline = "select count(*) as total from oms_charger_state_direct where  online_status = 0";
//		String sql2_d_offline = "select count(*) as total from oms_charger a,oms_charger_state_direct b where a.charger_type = 1 and online_status = 0 and a.valid_flag = 1 and b.valid_flag=1 and a.charger_id=b.charger_id ";
//		List<Map<String, Object>> list2_d_offline = omsStationDao.findDataBySql(sql2_d_offline, null);
//		Map<String, Object> map2_d_offline = list2_d_offline.get(0);
//		offlineNo_d = Integer.valueOf(map2_d_offline.get("total").toString());
//		//String sql2_a_offline = "select count(*) as total from oms_charger_state_alternate where  online_status = 0";
//		String sql2_a_offline = "select count(*) as total from oms_charger a,oms_charger_state_alternate b where a.charger_type = 2 and online_status = 0 and a.valid_flag = 1 and b.valid_flag=1 and a.charger_id=b.charger_id ";
//		List<Map<String, Object>> list2_a_offline = omsStationDao.findDataBySql(sql2_a_offline, null);
//		Map<String, Object> map2_a_offline = list2_a_offline.get(0);
//		offlineNo_a = Integer.valueOf(map2_a_offline.get("total").toString());
//		chargerOfflineNo = offlineNo_d + offlineNo_a;
		int chargerTotal=0,chargerErrorNo=0,chargerChargeNo=0,chargerBespeakNo=0,chargerFreeNo=0,chargerUseNo = 0,chargerSwipeNo = 0;
		int chargerFreeNo_alternate=0,chargerBespeakNo_alternate=0,chargerChargeNo_alternate=0,chargerErrorNo_alternate=0,chargerUseNo_alternate = 0,chargerSwipeNo_alternate = 0;
		int chargerFreeNo_direct=0,chargerBespeakNo_direct=0,chargerChargeNo_direct=0,chargerErrorNo_direct=0,chargerUseNo_direct = 0,chargerSwipeNo_direct = 0;
		//String sql2_a = "select charge_status,count(charge_status) as total from oms_charger_state_alternate group by charge_status";
		String sql2_a = "select b.charge_status,count(b.charge_status) as total from oms_charger a,oms_charger_state_alternate  b where a.charger_type = 2 and a.valid_flag = 1  and b.valid_flag=1 and a.charger_id=b.charger_id group by b.charge_status" ;
		List<Map<String, Object>> list2_a = omsStationDao.findDataBySql(sql2_a, null);
		if(list2_a.size()>0){
			for(Map<String, Object> map : list2_a){//0: 空闲;1: 预约;2 充电; 3 故障;4:占用中（针对双枪单充等情况）;5 刷卡中  8:离线
				if(map.get("charge_status").toString().equals("0")){
					chargerFreeNo_alternate= Integer.valueOf(map.get("total").toString());
				}else if(map.get("charge_status").toString().equals("1")){
					chargerBespeakNo_alternate = Integer.valueOf(map.get("total").toString());
				}else if(map.get("charge_status").toString().equals("2")){
					chargerChargeNo_alternate = Integer.valueOf(map.get("total").toString());
				}else if(map.get("charge_status").toString().equals("3")){
					chargerErrorNo_alternate = Integer.valueOf(map.get("total").toString());
				}else if(map.get("charge_status").toString().equals("4")){
					chargerUseNo_alternate = Integer.valueOf(map.get("total").toString());
				}else if(map.get("charge_status").toString().equals("5")){
					chargerSwipeNo_alternate = Integer.valueOf(map.get("total").toString());
				}else if(map.get("charge_status").toString().equals("8")){
					offlineNo_a = Integer.valueOf(map.get("total").toString());
				}
			}
		}
		//String sql2_d = "select charge_status,count(charge_status) as total from oms_charger_state_direct group by charge_status";
		String sql2_d = "select b.charge_status,count(b.charge_status) as total from oms_charger a,oms_charger_state_direct  b where a.charger_type = 1 and a.valid_flag = 1  and b.valid_flag=1 and a.charger_id=b.charger_id group by b.charge_status" ;
		List<Map<String, Object>> list2_d = omsStationDao.findDataBySql(sql2_d, null);
		if(list2_d.size()>0){
			for(Map<String, Object> map : list2_d){//0: 空闲;1: 预约;2 充电; 3 故障
				if(map.get("charge_status").toString().equals("0")){
					chargerFreeNo_direct = Integer.valueOf(map.get("total").toString());
				}else if(map.get("charge_status").toString().equals("1")){
					chargerBespeakNo_direct = Integer.valueOf(map.get("total").toString());
				}else if(map.get("charge_status").toString().equals("2")){
					chargerChargeNo_direct = Integer.valueOf(map.get("total").toString());
				}else if(map.get("charge_status").toString().equals("3")){
					chargerErrorNo_direct = Integer.valueOf(map.get("total").toString());
				}else if(map.get("charge_status").toString().equals("4")){
					chargerUseNo_direct = Integer.valueOf(map.get("total").toString());
				}else if(map.get("charge_status").toString().equals("5")){
					chargerSwipeNo_direct = Integer.valueOf(map.get("total").toString());
				}else if(map.get("charge_status").toString().equals("8")){
					offlineNo_d = Integer.valueOf(map.get("total").toString());
				}
			}
		}
		chargerOfflineNo = offlineNo_d + offlineNo_a;
		int chargerTotal_d = chargerFreeNo_direct + chargerChargeNo_direct + chargerBespeakNo_direct  + chargerUseNo_direct + chargerSwipeNo_direct + offlineNo_d + chargerErrorNo_direct; 
		int chargerTotal_a = chargerFreeNo_alternate + chargerChargeNo_alternate + chargerBespeakNo_alternate + chargerUseNo_alternate + chargerSwipeNo_alternate +  offlineNo_a + chargerErrorNo_alternate; 
		String charger_condition = "",bespeak_or_charge_condition ="";
		switch(charger_type){//charger_type:1为直流，2为交流，不传为查询全部
		case "1":
			chargerFreeNo = chargerFreeNo_direct;
			chargerErrorNo = chargerErrorNo_direct;
			chargerChargeNo = chargerChargeNo_direct;
			chargerBespeakNo = chargerBespeakNo_direct;
			chargerOfflineNo = offlineNo_d; 
			chargerTotal = chargerTotal_d;
			charger_condition = " and charger_type = 1 and valid_flag = 1 ";
			//bespeak_or_charge_condition = " and valid_flag = 1 and charger_id in (SELECT charger_id from oms_charger where charger_type = 1 and valid_flag = 1 )";
			bespeak_or_charge_condition = " and valid_flag = 1 and charger_id in (SELECT charger_id from oms_charger where charger_type = 1 )";
			break;
		case "2":
			chargerFreeNo = chargerFreeNo_alternate;
			chargerErrorNo = chargerErrorNo_alternate;
			chargerChargeNo = chargerChargeNo_alternate;
			chargerBespeakNo = chargerBespeakNo_alternate;
			chargerOfflineNo = offlineNo_a; 
			chargerTotal = chargerTotal_a;
			charger_condition = " and charger_type = 2 and valid_flag = 1 ";
			//bespeak_or_charge_condition = " and valid_flag = 1 and charger_id in (SELECT charger_id from oms_charger where charger_type = 2 and valid_flag = 1 )";
			bespeak_or_charge_condition = " and valid_flag = 1 and charger_id in (SELECT charger_id from oms_charger where charger_type = 2 )";
			break;
		default:
			chargerFreeNo = chargerFreeNo_direct + chargerFreeNo_alternate;
			chargerErrorNo = chargerErrorNo_direct + chargerErrorNo_alternate;
			chargerChargeNo =chargerChargeNo_direct + chargerChargeNo_alternate;
			chargerBespeakNo = chargerBespeakNo_direct + chargerBespeakNo_alternate;
			chargerOfflineNo = offlineNo_d + offlineNo_a; 
			chargerTotal = chargerTotal_d + chargerTotal_a;
			charger_condition = " and valid_flag = 1 ";
			//bespeak_or_charge_condition = " and valid_flag = 1 and charger_id in (SELECT charger_id from oms_charger where valid_flag = 1 )";
			bespeak_or_charge_condition = " and valid_flag = 1 and charger_id in (SELECT charger_id from oms_charger )";
			break;	
		}
//		chargerTotal = chargerFreeNo + chargerErrorNo + chargerChargeNo + chargerBespeakNo + chargerOfflineNo;
		//桩：上上月桩总数、上月桩总数、本月桩总数、本月预约数量、上月预约数量、本月充电数量、上月充电数量
		int twoMonthsPriorChargerNo,lastMonthChargerNo, thisMonthChargerNo,thisMonthBespeakNo,lastMonthBespeakNo,thisMonthChargeNo,lastMonthChargeNo;
		//按installation_time  create_time
		String sql3_twoMonthsPrior = "select count(*) as total from oms_charger  "
				+ "where create_time <date_sub(date_sub(date_format(now(),'%y-%m-%d'),"
				+ "interval extract(day from now())-1 day),interval 1 month)  "+charger_condition;
		List<Map<String, Object>> list3_twoMonthsPrior = omsStationDao.findDataBySql(sql3_twoMonthsPrior, null);
		Map<String, Object> map3_twoMonthsPrior = list3_twoMonthsPrior.get(0);
		twoMonthsPriorChargerNo = Integer.valueOf(map3_twoMonthsPrior.get("total").toString());
		String sql3_lastMonth = "select count(*) as total from oms_charger  where create_time <date_sub(date_sub(date_format(now(),"
				+ "'%y-%m-%d'),interval extract(day from now())-1 day),interval 0 month) "+charger_condition;;
		List<Map<String, Object>> list3_lastMonth = omsStationDao.findDataBySql(sql3_lastMonth, null);
		Map<String, Object> map3_lastMonth = list3_lastMonth.get(0);
		lastMonthChargerNo = Integer.valueOf(map3_lastMonth.get("total").toString());
		String sql3_thisMonth = "select count(*) as total from oms_charger where 1 = 1 "+charger_condition;
		List<Map<String, Object>> list3_thisMonth = omsStationDao.findDataBySql(sql3_thisMonth, null);
		Map<String, Object> map3_thisMonth = list3_thisMonth.get(0);
		thisMonthChargerNo = Integer.valueOf(map3_thisMonth.get("total").toString());
		String sql3_thisMonthBespeakNo = "select count(*) as total from oms_charger_bespeak_bill_record  where  "
				+ "date_format(start_time,'%Y-%m')=date_format(now(),'%Y-%m') and status in('4','5') "+bespeak_or_charge_condition;
		List<Map<String, Object>> list3_thisMonthBespeakNo = omsStationDao.findDataBySql(sql3_thisMonthBespeakNo, null);
		Map<String, Object> map3_thisMonthBespeakNo = list3_thisMonthBespeakNo.get(0);
		thisMonthBespeakNo = Integer.valueOf(map3_thisMonthBespeakNo.get("total").toString());
		String sql3_lastMonthBespeakNo = "select count(*) as total from oms_charger_bespeak_bill_record  where  "
				+ "date_format(start_time,'%Y-%m')=date_format(DATE_SUB(curdate(), INTERVAL 1 MONTH),'%Y-%m') and status in('4','5') "+bespeak_or_charge_condition;
		List<Map<String, Object>> list3_lastMonthBespeakNo = omsStationDao.findDataBySql(sql3_lastMonthBespeakNo, null);
		Map<String, Object> map3_lastMonthBespeakNo = list3_lastMonthBespeakNo.get(0);
		lastMonthBespeakNo = Integer.valueOf(map3_lastMonthBespeakNo.get("total").toString());
		String sql3_thisMonthChargeNo = "select count(*) as total from oms_charger_charge_bill_record  where "
				+ " date_format(start_time,'%Y-%m')=date_format(now(),'%Y-%m') and status in('5','6','7') "+bespeak_or_charge_condition;
		List<Map<String, Object>> list3_thisMonthChargeNo = omsStationDao.findDataBySql(sql3_thisMonthChargeNo, null);
		Map<String, Object> map3_thisMonthChargeNo = list3_thisMonthChargeNo.get(0);
		thisMonthChargeNo = Integer.valueOf(map3_thisMonthChargeNo.get("total").toString());
		String sql3_lastMonthChargeNo = "select count(*) as total from oms_charger_charge_bill_record  where  "
				+ "date_format(start_time,'%Y-%m')=date_format(DATE_SUB(curdate(), INTERVAL 1 MONTH),'%Y-%m') and status in('5','6','7')  "+bespeak_or_charge_condition;
		List<Map<String, Object>> list3_lastMonthChargeNo = omsStationDao.findDataBySql(sql3_lastMonthChargeNo, null);
		Map<String, Object> map3_lastMonthChargeNo = list3_lastMonthChargeNo.get(0);
		lastMonthChargeNo = Integer.valueOf(map3_lastMonthChargeNo.get("total").toString());
		
		omsHomePage.setChargerBespeakNo(chargerBespeakNo);
		omsHomePage.setChargerChargeNo(chargerChargeNo);
		omsHomePage.setChargerErrorNo(chargerErrorNo);
		omsHomePage.setChargerFreeNo(chargerFreeNo);
		omsHomePage.setChargerOfflineNo(chargerOfflineNo);
		omsHomePage.setChargerTotal(chargerTotal);
		omsHomePage.setLastMonthBespeakNo(lastMonthBespeakNo);
		omsHomePage.setLastMonthChargeNo(lastMonthChargeNo);
		omsHomePage.setLastMonthChargerNo(lastMonthChargerNo);
		omsHomePage.setMakingNo(makingNo);
		omsHomePage.setOfflineNo_a(offlineNo_a);
		omsHomePage.setOfflineNo_d(offlineNo_d);
		omsHomePage.setOperationNo(operationNo);
		omsHomePage.setPlanningNo(planningNo);
		omsHomePage.setStationTotal(stationTotal);
		omsHomePage.setThisMonthBespeakNo(thisMonthBespeakNo);
		omsHomePage.setThisMonthChargeNo(thisMonthChargeNo);
		omsHomePage.setThisMonthChargerNo(thisMonthChargerNo);
		omsHomePage.setTwoMonthsPriorChargerNo(twoMonthsPriorChargerNo);
		json.setCode("200");
		json.setMsg("ok");
		json.setPojo(omsHomePage);
		return json;
	}
//	JsonForMapDataList

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public JsonForMapDataList getMapDataInit(String current_state) {
		JsonForMapDataList json = new JsonForMapDataList();
		if(!StringUtil.isNumeric(current_state)){
			json.setCode("400");
			json.setMsg("current_state error");
			return json;
		}
		int stationTotal,stationActiveNo, stationPreinstallNo;
		List<OmsStation>  stationList = new ArrayList<OmsStation>();
		String sql_oms_station = "select count(*) as total from oms_station  where  valid_flag = 1  ";
		List<Map<String, Object>> list_oms_station = omsStationDao.findDataBySql(sql_oms_station, null);
		Map<String, Object> map_oms_station = list_oms_station.get(0);
		String sql_oms_station_external = "select count(*) as total from oms_station_external  where  valid_flag = 1  ";
		List<Map<String, Object>> list_sql_oms_station_external = omsStationDao.findDataBySql(sql_oms_station_external, null);
		Map<String, Object> map_sql_oms_station_external = list_sql_oms_station_external.get(0);
		stationTotal = Integer.valueOf(map_oms_station.get("total").toString()) + Integer.valueOf(map_sql_oms_station_external.get("total").toString());		
		String sql_stationActiveNo = "select count(*) as total from oms_station  where current_state = 1 and valid_flag = 1  ";
		List<Map<String, Object>> list_stationActiveNo = omsStationDao.findDataBySql(sql_stationActiveNo, null);
		Map<String, Object> map_stationActiveNo = list_stationActiveNo.get(0);
		stationActiveNo = Integer.valueOf(map_stationActiveNo.get("total").toString());		
		String sql_stationPreinstallNo = "select count(*) as total from oms_station  where current_state != 1 and valid_flag = 1  ";
		List<Map<String, Object>> list_stationPreinstallNo = omsStationDao.findDataBySql(sql_stationPreinstallNo, null);
		Map<String, Object> map_stationPreinstallNo = list_stationPreinstallNo.get(0);
		stationPreinstallNo = Integer.valueOf(map_stationPreinstallNo.get("total").toString());	
//		OmsStation station_query = new OmsStation();
		StringBuilder sb = new StringBuilder("select os.station_id,os.station_name,os.oper_merchant_id,os.district_code,os.total_charger,"
				+ " os.station_type,os.is_allow_open,os.address,os.current_state,os.direct_num,os.alternate_num,os.tel_no,os.is_rent,os.describes,os.total_charge,"
				+ " osl.coordinate_x,osl.coordinate_y from oms_station os ,oms_station_location osl where os.station_id = osl.station_id "
				+ " and osl.coordtype = 1");
		List<Map<String, Object>>  list_map = new ArrayList<Map<String, Object>>();
		switch(current_state){
			case "0":
//				stationList = omsStationDao.findAll(station_query);
				sb.append(" and os.valid_flag = 1 and osl.valid_flag = 1 ");
				list_map = omsStationDao.findDataBySql(sb.toString());//高德地图
				break;
			case "1":
//				station_query.setCurrent_state(1);
//				stationList = omsStationDao.findExample(station_query, null, null, null, null);
				sb.append(" and os.current_state = 1 ");
				list_map = omsStationDao.findDataBySql(sb.toString());//高德地图
				break;
			case "2":
//				station_query.setCurrent_state(2);
//				stationList = omsStationDao.findExample(station_query, null, null, null, null);
				sb.append(" and os.current_state = 1 ");
				list_map = omsStationDao.findDataBySql(sb.toString());//高德地图
				break;
			case "3":
//				station_query.setCurrent_state(3);
//				stationList = omsStationDao.findExample(station_query, null, null, null, null);
				sb.append(" and os.current_state = 3 ");
				list_map = omsStationDao.findDataBySql(sb.toString());//高德地图
				break;
			case "9":
//				stationList = omsStationDao.findListByCondition(station_query, "where current_state!=1");
				sb.append(" and os.current_state != 1 ");
				list_map = omsStationDao.findDataBySql(sb.toString());//高德地图
				break;
			default:
				break;
		}
		json.setStationActiveNo(stationActiveNo);
		json.setStationPreinstallNo(stationPreinstallNo);
		json.setStationTotal(stationTotal);
//		json.setList(stationList);
		json.setList(list_map);
		return json;
	}

	@Override
	public String getNewStationId(OmsStation omsStation) {
		//暂时以前6位作区号，模糊查询目前存在的区号的站点。
		String district_code = omsStation.getDistrict_code();//6位
		String oper_merchant_id = omsStation.getOper_merchant_id();//取运营商id后4位
		String stationId_query = district_code + oper_merchant_id.substring(oper_merchant_id.length() - 4, oper_merchant_id.length());
//		String sql = "select station_Id from oms_station where station_Id like '"+stationId_query+"%' order by station_Id desc ";
		OmsStation omsStation_1 = omsStationDao.findOneExampleByCondition(new OmsStation(),
				"where station_Id like '" + stationId_query + "%'  and LENGTH(station_Id) = 20 order by station_Id desc ");
		if(omsStation_1 == null){
			return stationId_query + "0000000001";
		}
		String stationId_old = omsStation_1.getStation_id();
		String serial_str = stationId_old.substring(10, 20);
		return stationId_old.substring(0,10)+StringUtil.complement(String.valueOf((Integer.valueOf(serial_str)+1)), 10);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public JsonCommon getStationByChargerId(String chargerId) {
		JsonCommon json  = new JsonCommon();
		OmsCharger charger_query= new OmsCharger();
		charger_query.setCharger_id(chargerId);
		OmsCharger charger = omsChargerDao.findOneExample(charger_query, null, null);
		if(charger == null){
			json.setCode("400");
			json.setMsg("this chargerId not in database ");
			return json;
		}
		
		if(StringUtil.isBlank(charger.getStation_id())){
			json.setCode("400");
			json.setMsg("this chargerId not own any station ");
			return json;
		}
		OmsStation station_query= new OmsStation();
		station_query.setStation_id(charger.getStation_id());;
		OmsStation station = omsStationDao.findOneExample(station_query, null, null);
		json.setCode("200");
		json.setMsg("ok");
		json.setPojo(station);
		return json;
	}

	@Override
	public OmsStation getStationById(String stationId) {
		OmsStation station_query= new OmsStation();
		station_query.setStation_id(stationId);
		return omsStationDao.findOneExample(station_query, null, null);
	}

	@Override
	public JsonForList getStationListByPage(OmsStationVO station, int pageNo, int pageSize, String sortName,
			int sortVal, String oper_id) {
		
		return null;
	}

	@Override
	public JsonForList getChargecountSummary(String startdate, String enddate, String year, String chargertype)
	{
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;
		if (!StringUtil.isBlank(year))
		{
			sql.append(" SELECT  DATE_FORMAT(b.start_time,'%Y-%m') chargedate, count(*) count   ");
			sql.append("   FROM oms_charger_charge_bill_record b   ");
			sql.append("  INNER JOIN oms_charger c on b.charger_id = c.charger_id ");
			sql.append("  WHERE b.valid_flag = 1     "); 
			sql.append("  AND b.status in('5','6','7') ");   //跟getChargeCountById保持一致查询条件，但是由于接口限制，此处必须跟oms_charger关联统计
			sql.append("    AND DATE_FORMAT(b.start_time, '%Y') = ?   ");
			if (!StringUtil.isBlank(chargertype))
				sql.append(" AND c.charger_type = ? ");
			sql.append("  GROUP BY DATE_FORMAT(b.start_time,'%Y-%m')  ");

			if (StringUtil.isBlank(chargertype))
				list_chargecount = omsStationDao.findDataBySql(sql.toString(), year);
			else
				list_chargecount = omsStationDao.findDataBySql(sql.toString(), year, chargertype);

			populateSummaryInfoByYear(list_chargecount, year, "chargedate", "count");
		}
		else
		{
			sql.append(" SELECT  DATE_FORMAT(b.start_time,'%Y-%m-%d') chargedate, count(*) count   ");
			sql.append("   FROM oms_charger_charge_bill_record b   ");
			sql.append("  INNER JOIN oms_charger c on b.charger_id = c.charger_id ");
			sql.append("  WHERE b.valid_flag = 1     "); 
			sql.append("  AND b.status in('5','6','7') ");   //跟getChargeCountById保持一致查询条件，但是由于接口限制，此处必须跟oms_charger关联统计
			sql.append("    AND date(b.start_time) BETWEEN date(?)   ");
			sql.append("    AND date(?)      ");
			if (!StringUtil.isBlank(chargertype))
				sql.append(" AND c.charger_type = ? ");
			sql.append("  GROUP BY date(b.start_time)  ");
			if (StringUtil.isBlank(chargertype))
				list_chargecount = omsStationDao.findDataBySql(sql.toString(), startdate, enddate);
			else
				list_chargecount = omsStationDao.findDataBySql(sql.toString(), startdate, enddate, chargertype);

			populateSummaryInfoByDate(list_chargecount,startdate, enddate, "chargedate", "count");
		}

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getReserveCountSummary(String startdate, String enddate, String year, String chargertype)
	{
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_reservecount = null;
		if (!StringUtil.isBlank(year))
		{
			sql.append("     SELECT DATE_FORMAT(s.start_time,'%Y-%m') reservedate,   count(*) count     ");
			sql.append("	   FROM oms_charger_bespeak_bill_record s     ");
			sql.append(" INNER JOIN oms_charger c on s.charger_id = c.charger_id ");
			sql.append("	  WHERE s.valid_flag = 1      ");
			sql.append("        AND s.status in('4','5')  ");   //跟getChargeCountById保持一致查询条件，但是由于接口限制，此处必须跟oms_charger关联统计
//			sql.append("	    AND date(s.start_time) BETWEEN date(?) AND date(?)     ");
			sql.append("        AND DATE_FORMAT(s.start_time, '%Y') = ?   ");
			sql.append("	    AND s.actual_end_time IS NOT NULL     ");
			if (!StringUtil.isBlank(chargertype))
				sql.append("    AND c.charger_type = ? ");
			sql.append("   GROUP BY DATE_FORMAT(s.start_time,'%Y-%m')  ");

			if (StringUtil.isBlank(chargertype))
				list_reservecount = omsStationDao.findDataBySql(sql.toString(), year);
			else
				list_reservecount = omsStationDao.findDataBySql(sql.toString(), year, chargertype);

			populateSummaryInfoByYear(list_reservecount, year, "reservedate", "count");
		}
		else
		{
			sql.append("     SELECT DATE_FORMAT(s.start_time,'%Y-%m-%d') reservedate,   count(*) count     ");
			sql.append("	   FROM oms_charger_bespeak_bill_record s     ");
			sql.append(" INNER JOIN oms_charger c on s.charger_id = c.charger_id ");
			sql.append("	  WHERE s.valid_flag = 1      ");
			sql.append("        AND s.status in('4','5')  ");   //跟getChargeCountById保持一致查询条件，但是由于接口限制，此处必须跟oms_charger关联统计
			sql.append("	    AND date(s.start_time) BETWEEN date(?) AND date(?)     ");
			sql.append("	    AND s.actual_end_time IS NOT NULL     ");
			if (!StringUtil.isBlank(chargertype))
				sql.append("    AND c.charger_type = ? ");
			sql.append("   GROUP BY date(s.start_time)  ");

			if (StringUtil.isBlank(chargertype))
				list_reservecount = omsStationDao.findDataBySql(sql.toString(), startdate, enddate);
			else
				list_reservecount = omsStationDao.findDataBySql(sql.toString(), startdate, enddate, chargertype);

			populateSummaryInfoByDate(list_reservecount,startdate, enddate, "reservedate", "count");
		}

		JsonForList json = new JsonForList();
		json.setList(list_reservecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getCarbonEmissionSummary(String startdate, String enddate, String year, String chargertype)
	{
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_carbonemission = null;
		if (!StringUtil.isBlank(year))
		{
			sql.append("     SELECT   DATE_FORMAT(b.start_time,'%Y-%m') chargedate,  sum(ifnull(b.this_reading,0)) *    ").append(CarbonEmissionConverter.CONVERT_RATE);
			sql.append("              carbon_emission    ");
			sql.append("       FROM  oms_charger_charge_bill_record b    ");
			sql.append(" INNER JOIN  oms_charger c on b.charger_id = c.charger_id ");
			sql.append("  WHERE b.valid_flag = 1     "); 
			sql.append("  AND b.status in('5','6','7') ");   //跟getChargeCountById保持一致查询条件，但是由于接口限制，此处必须跟oms_charger关联统计
			sql.append("        AND  DATE_FORMAT(b.start_time, '%Y') = ?   ");
			if (!StringUtil.isBlank(chargertype))
				sql.append("    AND  c.charger_type = ? ");
			sql.append("   GROUP BY  DATE_FORMAT(b.start_time,'%Y-%m')  ");

			if (StringUtil.isBlank(chargertype))
				list_carbonemission = omsStationDao.findDataBySql(sql.toString(), year);
			else
				list_carbonemission = omsStationDao.findDataBySql(sql.toString(), year, chargertype);

			populateSummaryInfoByYear(list_carbonemission, year, "chargedate", "carbon_emission");
		}
		else
		{
			sql.append("     SELECT   DATE_FORMAT(b.start_time,'%Y-%m-%d') chargedate,  sum(ifnull(b.this_reading,0)) *    ").append(CarbonEmissionConverter.CONVERT_RATE);
			sql.append("              carbon_emission    ");
			sql.append("       FROM  oms_charger_charge_bill_record b    ");
			sql.append(" INNER JOIN  oms_charger c on b.charger_id = c.charger_id ");
			sql.append("  WHERE b.valid_flag = 1     "); 
			sql.append("  AND b.status in('5','6','7') ");   //跟getChargeCountById保持一致查询条件，但是由于接口限制，此处必须跟oms_charger关联统计
			sql.append("        AND  date(b.start_time) BETWEEN date(?)  AND date(?)    ");
			if (!StringUtil.isBlank(chargertype))
				sql.append("    AND  c.charger_type = ? ");
			sql.append("   GROUP BY  date(b.start_time) ");

			if (StringUtil.isBlank(chargertype))
				list_carbonemission = omsStationDao.findDataBySql(sql.toString(), startdate, enddate);
			else
				list_carbonemission = omsStationDao.findDataBySql(sql.toString(), startdate, enddate, chargertype);

			populateSummaryInfoByDate(list_carbonemission,startdate, enddate, "chargedate", "carbon_emission");
		}


		JsonForList json = new JsonForList();
		json.setList(list_carbonemission);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	private void populateSummaryInfoByDate(List<Map<String, Object>> origin, String startdt, String enddt, final String keyname, String defaultvaluename)
	{
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		Calendar startdate = Calendar.getInstance();
		Calendar enddate = Calendar.getInstance();
		try
		{
			startdate.setTime(sdf.parse(startdt));
			enddate.setTime(sdf.parse(enddt));
		}
		catch (ParseException e)
		{
			log.error(e.getMessage());
			return;
		}

		ArrayList<String> keys_date = new ArrayList<>();
		for (Map<String, Object> item : origin)
		{
			keys_date.add(item.get(keyname).toString());
		}

		Calendar c = startdate;
		while (c.before(enddate) || c.equals(enddate))
		{
			String emptydate = sdf.format(c.getTime());
			if (!keys_date.contains(emptydate))
			{
				Map<String, Object> empty_item = new HashMap<>();
				empty_item.put(keyname, emptydate);
				empty_item.put(defaultvaluename, 0);
				origin.add(empty_item);
			}
			c.add(Calendar.DATE, 1);
		}

		Collections.sort(origin, new Comparator<Map<String, Object>>()
		{
			@Override
			public int compare(Map<String, Object> o1, Map<String, Object> o2)
			{
				try
				{
					Date date_o1 = sdf.parse(o1.get(keyname).toString());
					Date date_o2 = sdf.parse(o2.get(keyname).toString());
					if (date_o1.equals(date_o2))
						return 0;
					else if (date_o1.before(date_o2))
						return -1;
					else
						return 1;
				}
				catch (ParseException e)
				{
					e.printStackTrace();
					log.error(e.getMessage(), e);
					return 0;
				}
			}
		});
	}

	private void populateSummaryInfoByYear(List<Map<String, Object>> origin, String year, final String keyname, String defaultvaluename)
	{

		ArrayList<String> keys_date = new ArrayList<>();
		for (Map<String, Object> item : origin)
		{
			keys_date.add(item.get(keyname).toString());
		}

		for (int i = 1; i <= 12; i++)
		{
			String emptydate;
			if (i < 10)
				emptydate = year + "-0" + i;
			else
				emptydate = year + "-" + i;
			if (!keys_date.contains(emptydate))
			{
				Map<String, Object> empty_item = new HashMap<>();
				empty_item.put(keyname, emptydate);
				empty_item.put(defaultvaluename, 0);
				origin.add(empty_item);
			}
		}

		Collections.sort(origin, new Comparator<Map<String, Object>>()
		{
			@Override
			public int compare(Map<String, Object> o1, Map<String, Object> o2)
			{
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
				try
				{
					Date date_o1 = sdf.parse(o1.get(keyname).toString());
					Date date_o2 = sdf.parse(o2.get(keyname).toString());
					if (date_o1.equals(date_o2))
						return 0;
					else if (date_o1.before(date_o2))
						return -1;
					else
						return 1;
				}
				catch (ParseException e)
				{
					e.printStackTrace();
					log.error(e.getMessage(), e);
					return 0;
				}
			}
		});
	}

	@Override
	public JsonForList getChargeCountById(String startdate, String enddate, String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;

		sql.append("select date_format(start_time,'%Y-%m-%d') chargedate,count(1) count ");
		sql.append("from oms_charger_charge_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append("and valid_flag = 1 and status in('5','6','7') and start_time between date(?) and date(?)+1 ");
		sql.append("group by date_format(start_time,'%Y-%m-%d') "); 
		
		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, startdate, enddate);

		populateSummaryInfoByDate(list_chargecount,startdate, enddate, "chargedate", "count");
		

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getChargekwhById(String startdate, String enddate, String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;

		sql.append("select date_format(start_time,'%Y-%m-%d') chargedate,ifnull(sum(cast(this_reading as decimal(10,2))),0.00) kwh ");
		sql.append("from oms_charger_charge_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append("and valid_flag = 1 and status in('5','6','7') and start_time between date(?) and date(?)+1 ");
		sql.append("group by date_format(start_time,'%Y-%m-%d') ");
		
		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, startdate, enddate);

		populateSummaryInfoByDate(list_chargecount,startdate, enddate, "chargedate", "kwh");
		

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getChargeAmountById(String startdate, String enddate, String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;

		sql.append("select date_format(start_time,'%Y-%m-%d') chargedate,ifnull(sum(case this_amount when null  then this_amount_before else this_amount end),0.00)  amount ");
		sql.append("from oms_charger_charge_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append("and valid_flag = 1 and status in('5','6','7') and start_time between date(?) and date(?)+1 ");
		sql.append("group by date_format(start_time,'%Y-%m-%d') ");
		
		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, startdate, enddate);

		populateSummaryInfoByDate(list_chargecount,startdate, enddate, "chargedate", "amount");
		

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getReserveCountById(String startdate, String enddate, String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;

		sql.append("select date_format(start_time,'%Y-%m-%d') reservedate,count(1) count ");
		sql.append("from oms_charger_bespeak_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append("and valid_flag = 1 and status in('4','5') and start_time between date(?) and date(?)+1 ");
		sql.append("group by date_format(start_time,'%Y-%m-%d') "); 
		
		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, startdate, enddate);

		populateSummaryInfoByDate(list_chargecount,startdate, enddate, "reservedate", "count");

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getReserveTimeById(String startdate, String enddate, String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;

		sql.append("select date_format(start_time,'%Y-%m-%d') reservedate,cast(sum(UNIX_TIMESTAMP(actual_end_time)-UNIX_TIMESTAMP(start_time))/3600 as decimal(18,2)) reservetime ");
		sql.append("from oms_charger_bespeak_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append("and valid_flag = 1 and status in('4','5') and start_time between date(?) and date(?)+1 ");
		sql.append("group by date_format(start_time,'%Y-%m-%d') "); 
		
		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, startdate, enddate);

		populateSummaryInfoByDate(list_chargecount,startdate, enddate, "reservedate", "reservetime");		

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getReserveAmountById(String startdate, String enddate, String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;

		sql.append("select date_format(start_time,'%Y-%m-%d') reservedate,sum(case bespeak_deal_charge when null  then bespeak_deal_before else bespeak_deal_charge end) reserveaomunt ");
		sql.append("from oms_charger_bespeak_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append("and valid_flag = 1 and status in('4','5') and start_time between date(?) and date(?)+1 ");
		sql.append("group by date_format(start_time,'%Y-%m-%d') "); 
		
		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, startdate, enddate);

		populateSummaryInfoByDate(list_chargecount,startdate, enddate, "reservedate", "reserveaomunt");	

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getYearChargeCountById(String year, String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;
		
		sql.append("select a.chargedate,ifnull(b.count,0) count from (select concat('").append(year);
		sql.append("','-01') as chargedate union select concat('").append(year);
		sql.append("','-02') as chargedate union select concat('").append(year);
		sql.append("','-03') as chargedate union select concat('").append(year);
		sql.append("','-04') as chargedate union select concat('").append(year);
		sql.append("','-05') as chargedate union select concat('").append(year);
		sql.append("','-06') as chargedate union select concat('").append(year);
		sql.append("','-07') as chargedate union select concat('").append(year);
		sql.append("','-08') as chargedate union select concat('").append(year);
		sql.append("','-09') as chargedate union select concat('").append(year);
		sql.append("','-10') as chargedate union select concat('").append(year);
		sql.append("','-11') as chargedate union select concat('").append(year);
		sql.append("','-12') as chargedate ) a  left join (");

		sql.append("select date_format(start_time,'%Y-%m') month,count(1) count ");
		sql.append("from oms_charger_charge_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append("and valid_flag = 1 and status in('5','6','7') and date_format(start_time,'%Y')= ? ");
		sql.append("group by date_format(start_time,'%Y-%m') ");
		sql.append(") b  on a.chargedate=b.month order by chargedate ");		

		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, year);

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getYearChargekwhById(String year, String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;
		
		sql.append("select a.chargedate,ifnull(b.kwh,0) kwh from (select concat('").append(year);
		sql.append("','-01') as chargedate union select concat('").append(year);
		sql.append("','-02') as chargedate union select concat('").append(year);
		sql.append("','-03') as chargedate union select concat('").append(year);
		sql.append("','-04') as chargedate union select concat('").append(year);
		sql.append("','-05') as chargedate union select concat('").append(year);
		sql.append("','-06') as chargedate union select concat('").append(year);
		sql.append("','-07') as chargedate union select concat('").append(year);
		sql.append("','-08') as chargedate union select concat('").append(year);
		sql.append("','-09') as chargedate union select concat('").append(year);
		sql.append("','-10') as chargedate union select concat('").append(year);
		sql.append("','-11') as chargedate union select concat('").append(year);
		sql.append("','-12') as chargedate ) a  left join (");

		sql.append("select date_format(start_time,'%Y-%m') month, sum(cast(this_reading as decimal(10,2))) kwh ");
		sql.append("from oms_charger_charge_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append("and valid_flag = 1 and status in('5','6','7') and date_format(start_time,'%Y')= ? ");
		sql.append("group by date_format(start_time,'%Y-%m') ");
		sql.append(") b  on a.chargedate=b.month order by chargedate ");		

		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, year);

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getYearChargeAmountById(String year, String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;
		
		sql.append("select a.chargedate,ifnull(b.amount,0) amount from (select concat('").append(year);
		sql.append("','-01') as chargedate union select concat('").append(year);
		sql.append("','-02') as chargedate union select concat('").append(year);
		sql.append("','-03') as chargedate union select concat('").append(year);
		sql.append("','-04') as chargedate union select concat('").append(year);
		sql.append("','-05') as chargedate union select concat('").append(year);
		sql.append("','-06') as chargedate union select concat('").append(year);
		sql.append("','-07') as chargedate union select concat('").append(year);
		sql.append("','-08') as chargedate union select concat('").append(year);
		sql.append("','-09') as chargedate union select concat('").append(year);
		sql.append("','-10') as chargedate union select concat('").append(year);
		sql.append("','-11') as chargedate union select concat('").append(year);
		sql.append("','-12') as chargedate ) a  left join (");

		sql.append("select date_format(start_time,'%Y-%m') month, sum(case this_amount when null  then this_amount_before else this_amount end) amount ");
		sql.append("from oms_charger_charge_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append("and valid_flag = 1 and status in('5','6','7') and date_format(start_time,'%Y')= ? ");
		sql.append("group by date_format(start_time,'%Y-%m') ");
		sql.append(") b  on a.chargedate=b.month order by chargedate ");		

		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, year);

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getYearReserveCountById(String year, String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;
		
		sql.append("select a.reservedate ,ifnull(b.count,0) count from (select concat('").append(year);
		sql.append("','-01') as reservedate union select concat('").append(year);
		sql.append("','-02') as reservedate union select concat('").append(year);
		sql.append("','-03') as reservedate union select concat('").append(year);
		sql.append("','-04') as reservedate union select concat('").append(year);
		sql.append("','-05') as reservedate union select concat('").append(year);
		sql.append("','-06') as reservedate union select concat('").append(year);
		sql.append("','-07') as reservedate union select concat('").append(year);
		sql.append("','-08') as reservedate union select concat('").append(year);
		sql.append("','-09') as reservedate union select concat('").append(year);
		sql.append("','-10') as reservedate union select concat('").append(year);
		sql.append("','-11') as reservedate union select concat('").append(year);
		sql.append("','-12') as reservedate ) a  left join (");

		sql.append("select date_format(start_time,'%Y-%m') month, count(1) count ");
		sql.append("from oms_charger_bespeak_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append("and valid_flag = 1 and status in('4','5') and date_format(start_time,'%Y')= ? ");
		sql.append("group by date_format(start_time,'%Y-%m') ");
		sql.append(") b  on a.reservedate=b.month order by reservedate ");		

		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, year);

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getYearReserveTimeById(String year, String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;
		
		sql.append("select a.reservedate,ifnull(b.reservetime,0) reservetime from (select concat('").append(year);
		sql.append("','-01') as reservedate union select concat('").append(year);
		sql.append("','-02') as reservedate union select concat('").append(year);
		sql.append("','-03') as reservedate union select concat('").append(year);
		sql.append("','-04') as reservedate union select concat('").append(year);
		sql.append("','-05') as reservedate union select concat('").append(year);
		sql.append("','-06') as reservedate union select concat('").append(year);
		sql.append("','-07') as reservedate union select concat('").append(year);
		sql.append("','-08') as reservedate union select concat('").append(year);
		sql.append("','-09') as reservedate union select concat('").append(year);
		sql.append("','-10') as reservedate union select concat('").append(year);
		sql.append("','-11') as reservedate union select concat('").append(year);
		sql.append("','-12') as reservedate ) a  left join (");

		sql.append("select date_format(start_time,'%Y-%m') month, cast(sum(UNIX_TIMESTAMP(actual_end_time)-UNIX_TIMESTAMP(start_time))/3600 as decimal(18,2)) reservetime ");
		sql.append("from oms_charger_bespeak_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append("and valid_flag = 1 and status in('4','5') and date_format(start_time,'%Y')= ? ");
		sql.append("group by date_format(start_time,'%Y-%m') ");
		sql.append(") b  on a.reservedate=b.month order by reservedate ");		

		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, year);

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getYearReserveAmountById(String year, String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;
		
		sql.append("select a.reservedate,ifnull(b.reserveaomunt,0) reserveaomunt from (select concat('").append(year);
		sql.append("','-01') as reservedate union select concat('").append(year);
		sql.append("','-02') as reservedate union select concat('").append(year);
		sql.append("','-03') as reservedate union select concat('").append(year);
		sql.append("','-04') as reservedate union select concat('").append(year);
		sql.append("','-05') as reservedate union select concat('").append(year);
		sql.append("','-06') as reservedate union select concat('").append(year);
		sql.append("','-07') as reservedate union select concat('").append(year);
		sql.append("','-08') as reservedate union select concat('").append(year);
		sql.append("','-09') as reservedate union select concat('").append(year);
		sql.append("','-10') as reservedate union select concat('").append(year);
		sql.append("','-11') as reservedate union select concat('").append(year);
		sql.append("','-12') as reservedate ) a  left join (");

		sql.append("select date_format(start_time,'%Y-%m') month, sum(case bespeak_deal_charge when null  then bespeak_deal_before else bespeak_deal_charge end) reserveaomunt ");
		sql.append("from oms_charger_bespeak_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append("and valid_flag = 1 and status in('4','5') and date_format(start_time,'%Y')= ? ");
		sql.append("group by date_format(start_time,'%Y-%m') ");
		sql.append(") b  on a.reservedate=b.month order by reservedate ");		

		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, year);

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getChargeSummaryById(String id, String type) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_chargecount = null;
		
		sql.append("select a.count,a.kwh,ifnull(a.amount,0.00) amount,ifnull(a.carbon_emission,0.00) carbon_emission,b.reservecount,a.chargetime,ifnull(b.reserveaomunt,0.00) reserveaomunt ");
		sql.append("from (select  'm' m,count(1) count,ifnull(sum(cast(this_reading as decimal(10,2))),0.00 ) kwh, ");
		//concat(sec_to_time(ifnull(sum(UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time)),0)),'')
		sql.append("sum(case this_amount when null  then this_amount_before else this_amount end) amount,sum(this_reading)*").append(CarbonEmissionConverter.CONVERT_RATE).append(" carbon_emission, ifnull(sum(UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time)),0) chargetime ");
		sql.append("from oms_charger_charge_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		
		sql.append(" and valid_flag = 1 and status in('5','6','7') ) a left join ( ");
		sql.append("select  'm' m,count(1) reservecount, sum(case bespeak_deal_charge when null  then bespeak_deal_before else bespeak_deal_charge end) reserveaomunt ");
		sql.append("from oms_charger_bespeak_bill_record where ");
		if ("charger".equals(type)){
			sql.append(" charger_id = ? ");
		}else{
			sql.append(" station_id = ? ");
		}
		sql.append(" and valid_flag = 1 and status in('4','5') ) b  on a.m=b.m");
		
		list_chargecount = omsStationDao.findDataBySql(sql.toString(), id, id);

		JsonForList json = new JsonForList();
		json.setList(list_chargecount);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getStationDetailByStationId(String station_id) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_StationDetail = null;		

		sql.append("select  a.*,b.oper_name,c.name from oms_station a left join oms_operation_sp_list b on a.oper_merchant_id=b.oper_merchant_id ");
		sql.append("left join oms_normal_sp_list c on a.entity_id=c.merchant_id ");
		sql.append("where a.valid_flag=1 and  ");
	    sql.append("a.station_id = ? ");

	    list_StationDetail = omsStationDao.findDataBySql(sql.toString(), station_id);

		JsonForList json = new JsonForList();
		json.setList(list_StationDetail);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonForList getSimpleStationList(String station_id) {
		StringBuffer sql = new StringBuffer();
		List<Map<String, Object>> list_SimpleStation = null;		

		sql.append("select station_id,station_name,district_name,is_allow_open,current_state,direct_num+alternate_num  as charger_num ");
		sql.append("from oms_station where valid_flag=1 ");
		if (StringUtil.isNotBlank(station_id)) {
			sql.append("and station_id = ? ");
			 list_SimpleStation = omsStationDao.findDataBySql(sql.toString(), station_id);
		}else{
			 list_SimpleStation = omsStationDao.findDataBySql(sql.toString());
		}
	  
		JsonForList json = new JsonForList();
		json.setList(list_SimpleStation);
		json.setCode(JsonForList.SuccessCode);

		return json;
	}

	@Override
	public JsonCommon stationUpdateOrAddNotify(OmsStation station) {
		AppStationUpdateNotifyParam param = new AppStationUpdateNotifyParam();
		param.setProvinceCode(station.getDistrict_code().substring(0, 2) + "0000");
		Date update_time = new Date();// 更新时间
		SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
		param.setUpdateTime(dateFormat.format(update_time));
//		JsonCommon<String> result = systemAppServerRpcClient.stationUpdateNotify(param);
		JsonCommon<String> result = null;
		log.debug("Result:" + result.getCode());
		log.debug("Result:" + result.getMsg());

		return result;
	}

	@Override
	public JsonCommon stationDeleteNotify(List<String> list) {
		JsonForList json = new JsonForList();
		JsonCommon jsonc = new JsonCommon();
		
		if(list.size()<=0){
			jsonc.setCode(OmsConstant.ErrorCodeEnum.SqlExecException.value());
			jsonc.setMsg("stationIdList null");
			return jsonc;
		}
		StringBuilder sb =new StringBuilder("select distinct(left(district_code,2)) district_code from oms_station ");	
		sb.append(" where station_id in (");
		for(String id :list){
			sb.append("'"+id+"',");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append(")");
		
		List<Map<String, Object>> listTmp = omsStationDao.findDataBySql(sb.toString(), null);
		Date update_time = new Date();// 更新时间
		SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
		String strTime = dateFormat.format(update_time);
		JsonCommon<String> result = null;
		for(Map<String, Object> mapTmp : listTmp){
			//通知app更新
			AppStationUpdateNotifyParam appParam = new AppStationUpdateNotifyParam();
			appParam.setProvinceCode(mapTmp.get("district_code").toString() + "0000");	
			appParam.setUpdateTime(strTime);
//			result = systemAppServerRpcClient.stationUpdateNotify(appParam);
//			log.debug("Result:" + result.getCode());
//			log.debug("Result:" + result.getMsg());
		}
		return result;
	}

	@Override
	public List<Map<String, Object>> getNumberBindChargerOfStation(List<String> stationIdList) {
		StringBuffer sql = new StringBuffer();
		sql = sql.append("select count(1) cn,a.station_id station_id from oms.oms_station a,oms.oms_charger b where a.station_id=b.station_id and b.valid_flag=1 and a.station_id in(");
		for(String id :stationIdList){
			sql.append("'"+id+"',");
		}
		sql.deleteCharAt(sql.length()-1);
		sql.append(" ) group by a.station_id having count(1)>0 ");
		List<Map<String, Object>> list = omsStationDao.findDataBySql(sql.toString());
		return list;
	}

	@Override
	public List<StationExportVO> getExportData(String[] list_stationId)
	{
		StringBuffer sql = new StringBuffer();

		sql.append(" SELECT s.station_id, s.station_name, m.oper_name oper_merchant, s.district_name, s.circle, s.parking_type, s.parking_addr, s.total_charger, s.establish_time,  ");
		sql.append("     s.station_type, s.is_allow_open, s.address, s.current_state, s.direct_num, s.alternate_num, s.tel_no, s.is_rent, s.describes ");
		sql.append(" FROM oms_station s ");
		sql.append(" LEFT JOIN oms_operation_sp_list m ON s.oper_merchant_id = m.oper_merchant_id ");
		sql.append(" WHERE 1=1 ");

		if (list_stationId != null && list_stationId.length > 0)
		{
			sql.append(" AND s.station_id IN (");
			int i = 0;
			for (String stationId : list_stationId)
			{
				if (i == 0)
					sql.append("'").append(stationId).append("'");
				else
					sql.append(" , '").append(stationId).append("'");
				i++;
			}
			sql.append(" ) ");
		}
		return omsStationDao.exportStations(sql.toString());
	}

	@Override
	public JsonPageForList getSimpleStationPageList(OmsCommonParam buildQueryParam, String stationId, String isAllowOpen, String currentState, String searchStr) {
		try
		{
			StringBuffer sql = new StringBuffer();
			List<Map<String, Object>> list_SimpleStation = null;		
	
			sql.append("select station_id,station_name,district_name,is_allow_open,current_state,direct_num+alternate_num  as charger_num ");
			sql.append("from oms_station where valid_flag=1 ");
			if (StringUtil.isNotBlank(stationId)) {
				sql.append("and station_id = '"+stationId+"'");
			}
			if (StringUtil.isNotBlank(isAllowOpen)) {
				sql.append("and is_allow_open = '"+isAllowOpen+"'");
			}
			if (StringUtil.isNotBlank(currentState)) {
				sql.append("and current_state = '"+currentState+"'");
			}
			if (StringUtil.isNotBlank(searchStr)) {
				sql.append(" and (station_id like '%").
					append(searchStr).append("%' or station_name like '%").
					append(searchStr).append("%' or district_name like '%").
					append(searchStr).append("%')");
			}
			
			int total = 0;
			if (buildQueryParam.isQueryTotal())
			{
//				OmsStation omsStation =new OmsStation();
//				omsStation.setValid_flag(1);
//				if (StringUtil.isNotBlank(stationId)) {
//					omsStation.setStation_id(stationId);
//				}
//				if (StringUtil.isNotBlank(isAllowOpen)) {
//					omsStation.setIs_allow_open(Integer.parseInt(isAllowOpen));
//				}
//				if (StringUtil.isNotBlank(currentState)) {
//					omsStation.setCurrent_state(Integer.parseInt(currentState));
//				}
//				total = omsStationDao.queryTotalByObject(omsStation);
				
				try {
					total =  omsStationDao.queryTotalBySql(new OmsStation(), "select count(1) from ("+sql.toString()+") a", new ArrayList<Object>());
				} catch (Exception e) {
					total = 0;
					e.printStackTrace();
				}
			}

			//分页查询匹配
			if(buildQueryParam.getPageNo()!=null && buildQueryParam.getPageSize()!=null && buildQueryParam.getPageSize().intValue()!=0){
				sql.append(" limit ");
				sql.append((buildQueryParam.getPageNo()-1)*buildQueryParam.getPageSize());
				sql.append(",");
				sql.append(buildQueryParam.getPageSize());
			}
			
			list_SimpleStation = omsStationDao.findDataBySql(sql.toString());
	
			JsonPageForList jfl = new JsonPageForList();
			jfl.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
			jfl.setList(list_SimpleStation);
			jfl.setTotal(total);
			jfl.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
			return jfl;
		
		}
		catch (Exception e)
		{
			JsonPageForList jfl = new JsonPageForList();
			jfl.setCode(MsgCodeEnum.ERROR400.getMsgCode());
			jfl.setMsg(MsgCodeEnum.ERROR400.getMsgInfo());
			return jfl;
		}
	}

	@Override
	public OmsStationAll getStationAllById(String stationId)
	{
		OmsStationAll station_query= new OmsStationAll();
		station_query.setStation_id(stationId);
		return omsStationAllDao.findOneExample(station_query, null, null);
	}

}
